package com.example.nccdeploytool.controller;

import com.example.nccdeploytool.enums.FileType;
import com.example.nccdeploytool.HelloApplication;
import com.example.nccdeploytool.component.BubbleToast;
import com.example.nccdeploytool.entity.FileEntity;
import com.example.nccdeploytool.util.FXUtil;
import com.example.nccdeploytool.util.FileUtil;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.Glyph;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class HelloController implements Initializable {

    @FXML
    TabPane tabMain;

    @FXML
    private Label welcomeText;

    @FXML
    private VBox root;

    @FXML
    private MenuBar menuBar;


    //region 前端文件树
    @FXML
    private TreeView tvSrcFront;
    // 前端文本
    @FXML
    private TextField txtSrcFront;
    StringProperty txtSrcFrontProp;


    @FXML
    private TreeView tvDestFront;
    @FXML
    private TextField txtDestFront;
    //endregion

    //region 中央按钮
//    @FXML
//    private Button btnFrontLeft;
//    @FXML
//    private Button btnBackLeft;
    @FXML
    private Button btnFrontRight;
    @FXML
    private Button btnBackRight;
    //endregion


    private void addMenu() {
        // 创建文件菜单
        Menu fileMenu = new Menu("操作");
        MenuItem newItem = new MenuItem("打包位置");
        newItem.setOnAction(actionEvent -> {
            MenuItem source = (MenuItem) actionEvent.getSource();
            FXUtil.openWindow(source.getText(), "package-files.fxml");
        });
        MenuItem itemSSH = new MenuItem("登录ssh");
        itemSSH.setOnAction(actionEvent -> {
            // 获取事件源（触发事件的控件）
            MenuItem source = (MenuItem) actionEvent.getSource();
            FXUtil.openWindow(source.getText(), "ssh-login.fxml");
        });


        MenuItem itemSSHCmd = new MenuItem("ssh命令执行");
        itemSSHCmd.setOnAction(actionEvent -> {
            // 获取事件源（触发事件的控件）
            MenuItem source = (MenuItem) actionEvent.getSource();
            FXUtil.addFxmlTab(this.tabMain, source.getText(), "ssh-cmd.fxml", (event, ctl) -> {
                ((SshCmdController)ctl).cleanup();
            });
        });


        MenuItem itemSSHFile = new MenuItem("ssh文件管理");
        itemSSHFile.setOnAction(actionEvent -> {
            // 获取事件源（触发事件的控件）
            MenuItem source = (MenuItem) actionEvent.getSource();
            FXUtil.addFxmlTab(this.tabMain, source.getText(), "ssh-file.fxml", (event, ctl) -> {
                ((SshCmdController)ctl).cleanup();
            });
        });

        // 将菜单项添加到文件菜单
        fileMenu.getItems().addAll(newItem, itemSSH, itemSSHCmd,itemSSHFile);

        Menu helpMenu = new Menu("帮助");
        MenuItem aboutItem = new MenuItem("关于");

        // 将菜单项添加到帮助菜单
        helpMenu.getItems().add(aboutItem);

        // 将菜单添加到菜单栏
        menuBar.getMenus().addAll(fileMenu, helpMenu);


        // region 动态菜单

        // endregion



        // 为退出菜单项设置事件处理程序
//        exitItem.setOnAction(event -> HelloApplication.getPrimaryStage().close());
    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        try {

            // region 使用 FontAwesome 图标
            Glyph icon = new Glyph("FontAwesome", FontAwesome.Glyph.ARROW_LEFT);
            Glyph iconBack = new Glyph("FontAwesome", FontAwesome.Glyph.ARROW_LEFT);
            Glyph iconR = new Glyph("FontAwesome", FontAwesome.Glyph.ARROW_RIGHT);
            Glyph iconBackR = new Glyph("FontAwesome", FontAwesome.Glyph.ARROW_RIGHT);
            icon.setFontSize(14); // 设置图标大小
            iconBack.setFontSize(14); // 设置图标大小
            iconR.setFontSize(14); // 设置图标大小
            iconBackR.setFontSize(14); // 设置图标大小

//            // 将图标添加到按钮
//            btnFrontLeft.setGraphic(icon);
//            btnBackLeft.setGraphic(iconBack);

            btnFrontRight.setGraphic(iconR);
            btnBackRight.setGraphic(iconBackR);
            // endregion

            // 绑定数据
            txtSrcFrontProp = new SimpleStringProperty(txtSrcFront.getText());
            txtSrcFront.textProperty().bind(txtSrcFrontProp);


            FileEntity rootSrc = FileUtil.generateFileTree(txtSrcFront.getText());
            TreeItem copySrc = FileUtil.copy(rootSrc);
            tvSrcFront.setRoot(copySrc);


            FileEntity rootDest = FileUtil.generateFileTree(txtDestFront.getText());
            TreeItem copyDest = FileUtil.copy(rootDest);
            tvDestFront.setRoot(copyDest);

            setupTreeView(tvSrcFront);

            listenSizeChange();

            addMenu();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void listenSizeChange() {
        // 监听Scene尺寸变化
        root.sceneProperty().addListener((observable, oldScene, newScene) -> {
            if (newScene != null) {
                newScene.widthProperty().addListener((obs, oldWidth, newWidth) -> {
                    System.out.println("Scene宽度变化: " + newWidth);
                    tvSrcFront.refresh();
                });

                newScene.heightProperty().addListener((obs, oldHeight, newHeight) -> {
                    System.out.println("Scene高度变化: " + newHeight);
                    // 处理高度变化逻辑
                    tvSrcFront.refresh();
                });
            }
        });
    }


    /**
     * 设置拖拽
     */
    public void setupTreeView(TreeView treeView) {
    }


    /**
     * 前端移动逻辑
     *
     * @param actionEvent
     */
    public void btnFrontRightClick(ActionEvent actionEvent) {
        System.out.println("开始前端移动目录");
        // System.out.println("btnFrontRightClick");
        // 左侧文件
        TreeItem selectedItem = (TreeItem) tvSrcFront.getSelectionModel().getSelectedItem();
        if (selectedItem == null) {
            BubbleToast.show(HelloApplication.getPrimaryStage(), "左侧未选中");
            return;
        }
        // 右侧文件
        TreeItem selectedItemDest = (TreeItem) tvDestFront.getSelectionModel().getSelectedItem();
        if (selectedItemDest == null) {
            BubbleToast.show(HelloApplication.getPrimaryStage(), "右侧未选中");
            return;
        }
        FileEntity itemSel = (FileEntity) selectedItem.getValue(); // src文件
        FileEntity rootDest = (FileEntity) selectedItemDest.getValue(); // dest文件

        String fileType = itemSel.getFileType();

        ArrayList<String> copyItems = new ArrayList<>();

        // 获取所有文件
        if (FileType.DIR.getName().equals(fileType)) {
            System.out.println("移动目录:" + itemSel.getFilePath() + ",");
            copyItems.add(itemSel.getFilePath());
            // 如果是目录获取当前目录和子目录, 子文件
            FileUtil.dfsFileEntity(itemSel, (r, f) -> {
                System.out.println(f.getFilePath() + "," + f.getFilePath().substring(txtSrcFrontProp.getValue().length()));
                copyItems.add(f.getFilePath());
            });

            // 弹框显示要移动的文件
            FXUtil.openWindow("移动如下文件到" + rootDest.getFileName(), "copy-items.fxml");
        } else {
            System.out.println("移动文件:" + itemSel.getFileName());
        }

        // 弹框提示是否进行替换


        //
//        System.out.println(itemSel.toJSONString());
        System.out.println("开始前端移动结束");
    }

    public void btnFrontLeftClick(ActionEvent actionEvent) {
        System.out.println("btnFrontLeftClick");

    }

    public void btnBackRightClick(ActionEvent actionEvent) {
        System.out.println("btnBackRightClick");

    }

    public void btnBackLeftClick(ActionEvent actionEvent) {
        System.out.println("btnBackLeftClick");

    }

    //    // 在主窗口的控制器或主类中
//    @FXML
//    private void openCopyItemsWindow(String destFilename) {
//        try {
//            // 创建新的Stage
//            Stage newStage = new Stage();
//
//            // 设置标题
//            newStage.setTitle("移动如下文件到" + destFilename);
//
//            // 设置场景
//            FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("copy-items.fxml"));
//            Scene scene = new Scene(fxmlLoader.load(), 820, 640);
//            newStage.setScene(scene);
//
//            // 设置模态（可选）
//            newStage.initModality(Modality.APPLICATION_MODAL); // 阻止与其他窗口交互
//
//            // 设置所有者窗口（可选）
//            newStage.initOwner(HelloApplication.getPrimaryStage()); // primaryStage是主窗口的Stage
//
//            // 显示窗口
//            newStage.show();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}